/*
 * Copyright (c) 2017. 杭州端点网络科技有限公司.  All rights reserved.
 */

package com.jiantong.web.core.controller;

import com.jiantong.common.model.BaseLoginUser;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.model.User;
import com.jiantong.user.service.UserReadService;
import com.jiantong.web.core.util.LoginUserMaker;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author : panxin
 */
@Slf4j
@RestController
@RequestMapping
public class CommonUsers {

    @RpcConsumer
    private UserReadService<User> userReadService;

    /**
     * 登录用户信息, 读数据库
     *
     * @param userId 用户ID
     * @return 信息
     */
    @RequestMapping(value = "/api/user/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public Response<BaseLoginUser> findUserById(@PathVariable Long userId) {
        val userResp = userReadService.findById(userId);
        if (!userResp.isSuccess()) {
            log.warn("find user by id={} failed, error={}", userId, userResp.getError());
            return Response.fail(userResp.getError());
        }

        User user = userResp.getResult();
        return Response.ok(LoginUserMaker.from(user));
    }

    /**
     * 登录用户信息, thread local直接取
     *
     * @param request  请求
     * @param response 响应
     * @return 信息
     */
    @RequestMapping(value = "/api/user/login-user", method = RequestMethod.GET)
    public BaseLoginUser loginUser(HttpServletRequest request,
                                   HttpServletResponse response) {
        BaseLoginUser loginUser = UserUtil.getCurrentUser();

        // logs for test
        HttpSession session = request.getSession();
        String userId = String.valueOf(session.getAttribute("userId"));
        log.info("userId = {}", userId);
        log.info("api http request = {}, \r\n response = {}", request, response);
        log.info("login user = {}", loginUser);

        return loginUser;
    }

}
